<?php
session_start();
if (!isset($_SESSION['is_admin']) || $_SESSION['is_admin'] != 1) {
    header('Location: login.php');
    exit;
}

error_reporting(E_ALL);
ini_set('display_errors', 1);

// 数据库配置
$host = 'localhost';
$dbname = 'itops_help1_center';
$username = 'itops_help1_center';
$password = 'itops_help1_center';

$articleTable = 'article';
$categoryTable = 'categories';

$categories = [];
$error = '';
$success = '';

// 加载分类
try {
    $pdo = new PDO(
        "mysql:host=$host;dbname=$dbname;charset=utf8mb4",
        $username,
        $password,
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );
    $stmt = $pdo->query("SELECT id, name FROM $categoryTable ORDER BY sort_order ASC");
    $categories = $stmt instanceof PDOStatement ? $stmt->fetchAll() : [];
} catch (PDOException $e) {
    $error = "分类加载失败：" . $e->getMessage();
}

// 处理提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title'] ?? '');
    $categoryId = (int)($_POST['category_id'] ?? 0);
    $status = (int)($_POST['status'] ?? 0);
    $articleType = $_POST['article_type'] ?? 'doc';
    $content = '';

    // 处理内容
    if ($articleType === 'steps') {
        $steps = $_POST['steps'] ?? [];
        if (empty($steps)) {
            $error = "请至少添加一个操作步骤";
        } else {
            foreach ($steps as $index => $step) {
                $stepContent = trim($step['content'] ?? '');
                if (!empty($stepContent)) {
                    $content .= ($index + 1) . ". " . $stepContent . "\n\n";
                }
            }
            if (empty($content)) $error = "步骤内容不能为空";
        }
    } else {
        $content = trim($_POST['content'] ?? '');
        if (empty($content)) $error = "文章内容不能为空";
    }

    // 基础验证
    if (empty($title)) $error = "文章标题不能为空";
    elseif ($categoryId <= 0) $error = "请选择分类";
    elseif (!$error) {
        try {
            $pdo = new PDO(
                "mysql:host=$host;dbname=$dbname;charset=utf8mb4",
                $username,
                $password,
                [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
            );
            $stmt = $pdo->prepare("INSERT INTO $articleTable (
                title, content, category_id, status, article_type, create_time, update_time
            ) VALUES (:title, :content, :category_id, :status, :article_type, NOW(), NOW())");
            $stmt->execute([
                ':title' => $title,
                ':content' => $content,
                ':category_id' => $categoryId,
                ':status' => $status,
                ':article_type' => $articleType
            ]);
            header('Location: article.php?success=文章添加成功');
            exit;
        } catch (PDOException $e) {
            $error = "添加失败：" . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>新增文章 - 知识库管理系统</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.css">
    <link rel="stylesheet" href="css/common.css">
</head>
<body>
    <div class="admin-container">
        <aside class="admin-sidebar">
            <!-- 侧边栏内容同前 -->
            <div class="sidebar-header">
                <div class="sidebar-logo">
                    <i class="fas fa-cogs"></i>
                    <span>知识库管理</span>
                </div>
            </div>
            <ul class="nav-list">
                <li class="nav-item"><a href="index.php" class="nav-link"><i class="fas fa-home"></i><span>管理首页</span></a></li>
                <li class="nav-item"><a href="article.php" class="nav-link active"><i class="fas fa-file-alt"></i><span>文章管理</span></a></li>
                <li class="nav-item"><a href="category.php" class="nav-link"><i class="fas fa-folder"></i><span>分类管理</span></a></li>
                <li class="nav-item"><a href="version.php" class="nav-link"><i class="fas fa-sync-alt"></i><span>版本管理</span></a></li>
                <li class="nav-item"><a href="user.php" class="nav-link"><i class="fas fa-users"></i><span>用户管理</span></a></li>
                <li class="nav-item"><a href="logout.php" class="nav-link"><i class="fas fa-sign-out-alt"></i><span>退出登录</span></a></li>
            </ul>
        </aside>

        <main class="admin-content">
            <div class="content-wrapper">
                <div class="page-header">
                    <h1 class="page-title">新增文章</h1>
                    <a href="article.php" class="btn btn-outline"><i class="fas fa-arrow-left"></i>返回列表</a>
                </div>

                <?php if ($success): ?>
                    <div class="message message-success"><i class="fas fa-check-circle"></i><?php echo $success; ?></div>
                <?php endif; ?>
                <?php if ($error): ?>
                    <div class="message message-error"><i class="fas fa-exclamation-circle"></i><?php echo $error; ?></div>
                <?php endif; ?>

                <div class="form-card">
                    <form method="POST" action="" id="articleForm">
                        <div class="form-group">
                            <label class="form-label" for="title">文章标题 <span style="color: #EF4444;">*</span></label>
                            <input type="text" id="title" name="title" class="form-control" 
                                value="<?php echo htmlspecialchars($_POST['title'] ?? ''); ?>" placeholder="请输入文章标题">
                        </div>

                        <div class="form-row">
                            <div class="form-group">
                                <label class="form-label" for="category_id">所属分类 <span style="color: #EF4444;">*</span></label>
                                <select id="category_id" name="category_id" class="form-control">
                                    <option value="0">请选择分类</option>
                                    <?php foreach ($categories as $cate): ?>
                                        <option value="<?php echo $cate['id']; ?>" 
                                            <?php echo isset($_POST['category_id']) && $_POST['category_id'] == $cate['id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($cate['name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="form-group">
                                <label class="form-label" for="status">状态</label>
                                <select id="status" name="status" class="form-control">
                                    <option value="0" <?php echo isset($_POST['status']) && $_POST['status'] == 0 ? 'selected' : ''; ?>>草稿</option>
                                    <option value="1" <?php echo isset($_POST['status']) && $_POST['status'] == 1 ? 'selected' : ''; ?>>已发布</option>
                                </select>
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="form-label">文章类型</label>
                            <div class="radio-group">
                                <label class="radio-item">
                                    <input type="radio" name="article_type" value="doc" 
                                        <?php echo (!isset($_POST['article_type']) || $_POST['article_type'] == 'doc') ? 'checked' : ''; ?>>
                                    <span class="radio-custom"></span>
                                    <span>说明文档</span>
                                </label>
                                <label class="radio-item">
                                    <input type="radio" name="article_type" value="steps" 
                                        <?php echo isset($_POST['article_type']) && $_POST['article_type'] == 'steps' ? 'checked' : ''; ?>>
                                    <span class="radio-custom"></span>
                                    <span>操作步骤</span>
                                </label>
                            </div>
                        </div>

                        <!-- 说明文档编辑器 -->
                        <div id="doc_content_group" class="form-group">
                            <label class="form-label" for="content">文章内容 <span style="color: #EF4444;">*</span></label>
                            <div class="markdown-editor">
                                <textarea id="content" name="content"><?php echo htmlspecialchars($_POST['content'] ?? ''); ?></textarea>
                            </div>
                        </div>

                        <!-- 步骤文档表单 -->
                        <div id="steps_content_group" class="form-group" style="display: none;">
                            <label class="form-label">操作步骤 <span style="color: #EF4444;">*</span></label>
                            <div class="steps-container" id="steps_container"></div>
                            <button type="button" class="add-step-btn" id="add_step_btn">
                                <i class="fas fa-plus"></i> 添加步骤
                            </button>
                        </div>

                        <div class="form-actions">
                            <div>
                                <button type="button" class="btn btn-outline" id="import_btn">
                                    <i class="fas fa-upload"></i> 导入
                                    <div class="tooltip">
                                        <i class="fas fa-info-circle tooltip-icon"></i>
                                        <span class="tooltip-text">
                                            导入支持.md格式文件<br>
                                            导入后会覆盖当前内容<br>
                                            步骤文档建议按"1. 内容"格式编写
                                        </span>
                                    </div>
                                </button>
                                <button type="button" class="btn btn-outline" id="export_btn" style="margin-left: 0.5rem;">
                                    <i class="fas fa-download"></i> 导出
                                </button>
                            </div>
                            <div>
                                <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i>保存文章</button>
                                <a href="article.php" class="btn btn-outline" style="margin-left: 0.5rem;">取消</a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </main>
    </div>

    <!-- 上传弹窗 -->
    <div class="modal-backdrop" id="upload_modal">
        <div class="modal">
            <div class="modal-header">
                <h3 class="modal-title">上传文件</h3>
                <button class="modal-close" id="close_upload_modal">&times;</button>
            </div>
            <div class="modal-body">
                <form id="upload_form" enctype="multipart/form-data">
                    <input type="hidden" name="type" id="upload_type">
                    <div class="form-group">
                        <label class="form-label">选择文件</label>
                        <input type="file" name="file" class="form-control" accept="image/*,.pdf,.doc,.docx,.mp4,.webm">
                        <small style="color: #64748B; margin-top: 0.5rem; display: block;">
                            支持格式：图片(png/jpg/gif)、文档(pdf/doc)、视频(mp4/webm)，最大5MB
                        </small>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button class="btn btn-outline" id="cancel_upload">取消</button>
                <button class="btn btn-primary" id="do_upload">上传</button>
            </div>
        </div>
    </div>

    <!-- 导入弹窗 -->
    <div class="modal-backdrop" id="import_modal">
        <div class="modal">
            <div class="modal-header">
                <h3 class="modal-title">导入Markdown文件</h3>
                <button class="modal-close" id="close_import_modal">&times;</button>
            </div>
            <div class="modal-body">
                <form id="import_form" enctype="multipart/form-data">
                    <div class="form-group">
                        <label class="form-label">选择.md文件</label>
                        <input type="file" name="import_file" class="form-control" accept=".md" required>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button class="btn btn-outline" id="cancel_import">取消</button>
                <button class="btn btn-primary" id="do_import">导入</button>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.js"></script>
    <script>
        let simplemde;
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化Markdown编辑器
            simplemde = new SimpleMDE({
                element: document.getElementById("content"),
                autoDownloadFontAwesome: false,
                spellChecker: false,
                toolbar: [
                    "bold", "italic", "|",
                    "heading-1", "heading-2", "heading-3", "|",
                    "unordered-list", "ordered-list", "|",
                    {
                        name: "image",
                        action: function customFunction(editor) {
                            document.getElementById("upload_type").value = "image";
                            document.getElementById("upload_modal").classList.add("show");
                        },
                        className: "fa fa-image",
                        title: "插入图片"
                    },
                    {
                        name: "file",
                        action: function customFunction(editor) {
                            document.getElementById("upload_type").value = "file";
                            document.getElementById("upload_modal").classList.add("show");
                        },
                        className: "fa fa-file",
                        title: "插入文档"
                    },
                    {
                        name: "video",
                        action: function customFunction(editor) {
                            document.getElementById("upload_type").value = "video";
                            document.getElementById("upload_modal").classList.add("show");
                        },
                        className: "fa fa-video",
                        title: "插入视频"
                    },
                    "|", "preview", "fullscreen"
                ]
            });

            // 文章类型切换
            const radioItems = document.querySelectorAll('input[name="article_type"]');
            const docGroup = document.getElementById('doc_content_group');
            const stepsGroup = document.getElementById('steps_content_group');
            const stepsContainer = document.getElementById('steps_container');

            function toggleType() {
                const isSteps = document.querySelector('input[name="article_type"][value="steps"]').checked;
                docGroup.style.display = isSteps ? 'none' : 'block';
                stepsGroup.style.display = isSteps ? 'block' : 'none';
                if (isSteps && stepsContainer.children.length === 0) addStep();
            }

            radioItems.forEach(radio => radio.addEventListener('change', toggleType));
            toggleType(); // 初始化

            // 步骤管理
            window.addStep = function(stepData = {}) {
                const index = stepsContainer.children.length;
                const step = document.createElement('div');
                step.className = 'step-item';
                step.innerHTML = `
                    <div class="step-header">
                        <div class="step-title">步骤 ${index + 1}</div>
                        <button type="button" class="remove-step"><i class="fas fa-times"></i></button>
                    </div>
                    <div class="form-group">
                        <label class="form-label">步骤内容</label>
                        <textarea name="steps[${index}][content]" class="form-control" 
                            placeholder="请输入步骤详细内容">${stepData.content ? htmlEscape(stepData.content) : ''}</textarea>
                    </div>
                `;
                stepsContainer.appendChild(step);

                // 删除步骤
                step.querySelector('.remove-step').addEventListener('click', function() {
                    if (stepsContainer.children.length > 1) {
                        step.remove();
                        renumberSteps();
                    } else {
                        alert('至少保留一个步骤');
                    }
                });
            }

            // 重新编号
            function renumberSteps() {
                Array.from(stepsContainer.children).forEach((el, i) => {
                    el.querySelector('.step-title').textContent = `步骤 ${i + 1}`;
                    el.querySelector('textarea').name = `steps[${i}][content]`;
                });
            }

            document.getElementById('add_step_btn').addEventListener('click', addStep);

            // 上传文件
            const uploadModal = document.getElementById('upload_modal');
            document.getElementById('close_upload_modal').addEventListener('click', () => uploadModal.classList.remove('show'));
            document.getElementById('cancel_upload').addEventListener('click', () => uploadModal.classList.remove('show'));

            document.getElementById('do_upload').addEventListener('click', function() {
                const formData = new FormData(document.getElementById('upload_form'));
                fetch('upload.php', { method: 'POST', body: formData })
                    .then(res => res.json())
                    .then(data => {
                        if (data.success) {
                            const type = document.getElementById('upload_type').value;
                            let markdown = '';
                            if (type === 'image') markdown = `![图片](${data.url})`;
                            else if (type === 'video') markdown = `<video src="${data.url}" controls width="100%"></video>`;
                            else markdown = `[文档](${data.url})`;
                            
                            simplemde.value(simplemde.value() + '\n' + markdown + '\n');
                            uploadModal.classList.remove('show');
                        } else {
                            alert('上传失败：' + data.msg);
                        }
                    })
                    .catch(err => alert('上传出错：' + err));
            });

            // 导入导出
            const importModal = document.getElementById('import_modal');
            document.getElementById('import_btn').addEventListener('click', () => importModal.classList.add('show'));
            document.getElementById('close_import_modal').addEventListener('click', () => importModal.classList.remove('show'));
            document.getElementById('cancel_import').addEventListener('click', () => importModal.classList.remove('show'));

            document.getElementById('do_import').addEventListener('click', function() {
                const file = document.querySelector('input[name="import_file"]').files[0];
                if (!file) { alert('请选择文件'); return; }
                
                const reader = new FileReader();
                reader.onload = function(e) {
                    const content = e.target.result;
                    const isSteps = document.querySelector('input[name="article_type"][value="steps"]').checked;
                    
                    if (isSteps) {
                        // 清空现有步骤
                        stepsContainer.innerHTML = '';
                        // 按行分割（简单处理）
                        const lines = content.split('\n');
                        lines.forEach(line => {
                            line = line.trim();
                            if (line) {
                                // 移除数字前缀
                                const stepContent = line.replace(/^\d+\.\s*/, '');
                                addStep({ content: stepContent });
                            }
                        });
                    } else {
                        simplemde.value(content);
                    }
                    importModal.classList.remove('show');
                };
                reader.readAsText(file);
            });

            // 导出
            document.getElementById('export_btn').addEventListener('click', function() {
                const isSteps = document.querySelector('input[name="article_type"][value="steps"]').checked;
                let content = '';
                
                if (isSteps) {
                    const steps = stepsContainer.querySelectorAll('textarea');
                    steps.forEach((step, i) => {
                        const text = step.value.trim();
                        if (text) content += (i + 1) + '. ' + text + '\n\n';
                    });
                } else {
                    content = simplemde.value();
                }

                const blob = new Blob([content], { type: 'text/markdown' });
                const a = document.createElement('a');
                a.href = URL.createObjectURL(blob);
                a.download = (document.getElementById('title').value || '未命名') + '.md';
                a.click();
            });

            // HTML转义
            function htmlEscape(str) {
                return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
                    .replace(/"/g, '&quot;').replace(/'/g, '&#039;');
            }
        });
    </script>
</body>
</html>